package com.hake.test.jedis;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;

import com.alibaba.fastjson.JSON;

/**
 * Protostuff Google高性能序列化工具类
 * @author yhaoquan
 *
 */
@SuppressWarnings("unchecked")
public class BytesUtil {

	
	public static <T> byte[] toBytes(T obj) {
		RuntimeSchema<T> schema = (RuntimeSchema<T>) RuntimeSchema.createFrom(obj.getClass()) ;
		return ProtostuffIOUtil.toByteArray(obj, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
	}
	
	public static <T> T bytesToObject(byte[] bytes, Class<T> clazz) {
		RuntimeSchema<T> schema = (RuntimeSchema<T>) RuntimeSchema.createFrom(clazz) ;
		T t = schema.newMessage() ;
		ProtostuffIOUtil.mergeFrom(bytes, t, schema);
		return t;
	}
	
	public static byte[] keyToBytes(String key) {
		RuntimeSchema<String> schema = (RuntimeSchema<String>) RuntimeSchema.createFrom(key.getClass()) ;
		return ProtostuffIOUtil.toByteArray(key, schema, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
	}
	
	public static String keyFromBytes(byte[] bytes) {
		RuntimeSchema<String> schema = (RuntimeSchema<String>) RuntimeSchema.createFrom(String.class) ;
		String t = schema.newMessage() ;
		ProtostuffIOUtil.mergeFrom(bytes, t, schema);
		return t;
	}
	
	
	public static void main(String[] args) throws InstantiationException, IllegalAccessException {
		Person p = new Person() ;
		p.setName("要花钱");
		p.setAge(23);
		p.setSex("男");
		
		System.out.println("---------------------");
		
		byte[] bytesArray = toBytes(p) ;
		System.out.println(bytesArray);
		Person pp = bytesToObject(bytesArray, Person.class) ;
		System.out.println(JSON.toJSON(pp));
		
		/*byte[] bytesArray2 = toBytesArray("Hello".getBytes()) ;
		System.out.println(bytesArray2);
		String object = toObject(bytesArray2, String.class) ;
		System.out.println(object);*/
		
		
		/*RuntimeSchema<String> s =  RuntimeSchema.createFrom(String.class) ;
		byte[] byteArray = ProtostuffIOUtil.toByteArray(new String("Hello"), s, LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
		System.out.println(byteArray);
		
		String object = toObject(byteArray, String.class) ;
		System.out.println(object);*/
		
		/*byte[] keyToBytes = keyToBytes("Hello") ;
		System.out.println(keyToBytes);
		System.out.println(keyFromBytes(keyToBytes));*/
		
		byte[] serialize = ProtoStuffSerializerUtil.serialize("Hello") ;
		String deserialize = ProtoStuffSerializerUtil.deserialize(serialize, String.class) ;
		System.out.println(deserialize);
	}
	
}
